<template>
  <div>
    <vant-field
      label="车牌号码"
      :ref="'field'"
      v-model="item.vehicleNo"
      placeholder="请输入"
      input-align="right"
      :key="'field'"
      :rules="[{ required:true }]"
      @touchstart="clickVehicleNo(item)"
      @input="input(item)"
    />
    <app-dropdown-search
      v-model="item.vehicleNo"
      :key="'dropSearch'"
      ref="dropSearch"
      :getOptions="getOptions"
      :immediate="item._immediateSearch"
      @change="changeVehicle"
      @close="close"
    ></app-dropdown-search>
  </div>
</template>

<script>
import { deepClone } from '@utils/index'

import { getHistoryVehicles } from '@apis/history'
import { getOverflowAutoEl, scrollToEle } from '@utils/style'

export default {
  name: 'VehicleSearch',
  props: {
    item: {
      type: Object,
      default() {
        return {}
      }
    },
    type: {
      type: String,
      default: '' // select
    }
  },
  data() {
    return {
      val: deepClone(this.item),
      isChange: false
    }
  },
  methods: {
    clickVehicleNo(item) {
      item._immediateSearch = true;

      const field = this.$refs['field'].$el;
      this.$_autoEl = this.$_autoEl || getOverflowAutoEl(field);
      const scroll = scrollToEle(field, this.$_autoEl);
      const timer= setTimeout(()=>{
        clearTimeout(timer)
      scroll &&  field.querySelector('input').focus();
      },300);
    },
    getOptions() {
      return getHistoryVehicles().then(res => {
        const { data = [] } = res || {}
        return data.map(item => ({ ...item, value: item.vehicleNo, text: item.vehicleNo }))
      })
    },
    input() {
      this.$emit('input', ...arguments)
      // this.selectId
    },
    close() {
      //  this.$emit('change',{})
      if (this.isChange !== true) {
        this.val._immediateSearch = false;
        this.type === 'select' && this.$emit('change', this.val)
      } else {
        this.item._immediateSearch = false;
      }

      this.$nextTick(() => {
        this.isChange = false;
      })
    },
    changeVehicle(item) {
      this.val = deepClone(item)
      this.isChange = true


      this.$emit('change', ...arguments)
    }
  }
}
</script>

<style lang="less" scoped>
</style>